#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <sys/time.h>
#include "tbf.h"

#define BUFSIZE	32
#define CPS		10	 // 速率
#define BURST	((CPS) * 10) // 上限
#define CNT		10

int mycpy_sysio(int rfd, int wfd);

int main(int argc, char *argv[])
{
    int fd1;

    if (argc < 2)
        return 1;

    fd1 = open(argv[1], O_RDONLY);
    if (-1 == fd1) {
        // 打印失败的原因
        printf("errno:%d, err_string:%s\n", errno, strerror(errno));
        perror("open()函数调用失败");
        return 1;
    }

    mycpy_sysio(fd1, 1);

    close(fd1);

    return 0;
}

int mycpy_sysio(int rfd, int wfd)
{
    char buf[BUFSIZE] = {0};
    int cnt;
    int td;

    td = tbf_init(CPS, BURST);

    while (1) {
        while ((cnt = tbf_fetch_token(td, CNT)) == 0);
        
        memset(buf, 0, BUFSIZE);
        cnt = read(rfd, buf, cnt);
        if (0 == cnt)
            break;
        else if (-1 == cnt) {
            perror("失败函数是read()");
            return -1;
        }
        write(wfd, buf, cnt);	
    }

    tbf_destroy(td);

    return 0;
}




